import os
import signal
import subprocess
import shlex
import time
from common.logger import log


class Executor:
    # params
    # run_desc: {desc: XX, command: XX, exec_dir: XX}
    def __init__(self, desc, command, exec_dir='.', debug=0):
        self.desc = desc
        self.command = command
        self.exec_dir = exec_dir
        self.timeout = None
        self.debug = debug
        self.start_time = 0
        self.end_time = 0
        self.elapsed_time = 0
        self.log_file = "{}.log".format(os.path.join(self.exec_dir, self.desc))

    def parse_cmd(self):
        cmd = shlex.split(self.command)
        return cmd

    def exec(self):
        if self.debug:
            log.info('cmd: {}'.format(self.command))

        cmd = self.parse_cmd()
        with open(self.log_file, "w+") as f:
            f.write("exec commond: {}".format(self.command))

        self.start_time = time.time()
        process = subprocess.Popen(cmd,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.STDOUT,
                                   shell=False,
                                   universal_newlines=True,
                                   cwd=self.exec_dir)

        with open(self.log_file, "w+") as logfile:
            for line in process.stdout:
                logfile.write(line)
                if self.debug:
                    log.debug("{}: {}".format(self.desc, line.strip()))

        try:
            stdout, _ = process.communicate(timeout=self.timeout)
            self.end_time = time.time()

        except subprocess.TimeoutExpired:
            process.send_signal(signal.SIGINT)
            stdout, _ = process.communicate()

        return process.returncode
